<template>
  <div class="nutrition-dashboard">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <n-button quaternary circle @click="$router.back()">
        <n-icon :size="20">
          <ArrowBack />
        </n-icon>
      </n-button>
      <h2>营养仪表盘</h2>
      <div style="width: 40px;"></div>
    </div>

    <!-- 日期选择 -->
    <div class="date-selector">
      <n-date-picker
        v-model:value="selectedDateTimestamp"
        type="date"
        clearable
        style="width: 100%"
        placeholder="选择日期"
      />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
    </div>

    <!-- 无数据状态 -->
    <div v-else-if="!nutritionData" class="empty-state">
      <n-icon :size="64" color="#ccc">
        <StatsChart />
      </n-icon>
      <p>该日期没有饮食记录</p>
      <n-button type="primary" @click="$router.push('/events/create')">
        添加饮食记录
      </n-button>
    </div>

    <!-- 营养数据展示 -->
    <div v-else class="nutrition-content">
      <!-- 总体评分 -->
      <div class="overall-score">
        <h3>今日营养充足度</h3>
        <div class="score-circle">
          <n-progress
            type="circle"
            :percentage="overallScore"
            :stroke-width="12"
            :color="getScoreColor(overallScore)"
          >
            <div class="score-text">
              <div class="score-value">{{ Math.round(overallScore) }}%</div>
              <div class="score-label">{{ getScoreLabel(overallScore) }}</div>
            </div>
          </n-progress>
        </div>
      </div>

      <!-- 宏量营养素能量分析 -->
      <div class="macro-analysis">
        <h3>宏量营养素能量分析</h3>
        <div class="macro-chart">
          <div class="macro-item">
            <div class="macro-label">碳水化合物</div>
            <n-progress
              type="line"
              :percentage="macroNutrients.carb.percentage"
              :color="getMacroColor('carb', macroNutrients.carb.percentage)"
              :height="24"
            >
              <span class="progress-text">
                {{ macroNutrients.carb.grams }}g / {{ macroNutrients.carb.kcal }}kcal ({{ Math.round(macroNutrients.carb.percentage) }}%)
              </span>
            </n-progress>
            <div class="macro-recommendation">推荐: 50-65%</div>
          </div>

          <div class="macro-item">
            <div class="macro-label">蛋白质</div>
            <n-progress
              type="line"
              :percentage="macroNutrients.protein.percentage"
              :color="getMacroColor('protein', macroNutrients.protein.percentage)"
              :height="24"
            >
              <span class="progress-text">
                {{ macroNutrients.protein.grams }}g / {{ macroNutrients.protein.kcal }}kcal ({{ Math.round(macroNutrients.protein.percentage) }}%)
              </span>
            </n-progress>
            <div class="macro-recommendation">推荐: 10-20%</div>
          </div>

          <div class="macro-item">
            <div class="macro-label">脂肪</div>
            <n-progress
              type="line"
              :percentage="macroNutrients.fat.percentage"
              :color="getMacroColor('fat', macroNutrients.fat.percentage)"
              :height="24"
            >
              <span class="progress-text">
                {{ macroNutrients.fat.grams }}g / {{ macroNutrients.fat.kcal }}kcal ({{ Math.round(macroNutrients.fat.percentage) }}%)
              </span>
            </n-progress>
            <div class="macro-recommendation">推荐: 20-30%</div>
          </div>
        </div>
      </div>

      <!-- 营养素详细列表 -->
      <div class="nutrients-list">
        <h3>营养素详细统计</h3>
        
        <n-collapse>
          <n-collapse-item
            v-for="group in nutrientGroups"
            :key="group.majorCategory.category_id"
            :title="group.majorCategory.category_name"
          >
            <div class="nutrient-items">
              <div
                v-for="field in group.fields"
                :key="field.key"
                class="nutrient-item"
              >
                <div class="nutrient-header">
                  <span class="nutrient-name">{{ field.label }}</span>
                  <span class="nutrient-value">
                    {{ getNutrientIntake(field.key) }} {{ field.unit }}
                  </span>
                </div>
                
                <div v-if="getNutrientRecommendation(field.nutrientId)" class="nutrient-progress">
                  <n-progress
                    type="line"
                    :percentage="getNutrientAdequacy(field.key, field.nutrientId)"
                    :color="getNutrientStatusColor(field.key, field.nutrientId)"
                    :height="8"
                  />
                  <div class="nutrient-info">
                    <span class="recommendation">
                      推荐: {{ formatRecommendation(field.nutrientId) }}
                    </span>
                    <span class="status" :style="{ color: getNutrientStatusColor(field.key, field.nutrientId) }">
                      {{ getNutrientStatusText(field.key, field.nutrientId) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </n-collapse-item>
        </n-collapse>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ArrowBack, StatsChart } from '@vicons/ionicons5'
import { useEventsStore } from '@/stores/events'
import { formatDate } from '@/utils/date'
import type { FoodIntake, Food } from '@/types'
import {
  getNutrientFieldGroups,
  getNutrientRecommendation,
  calculateNutrientAdequacy,
  evaluateNutrientStatus
} from '@/data/nutrientCategories'

const eventsStore = useEventsStore()

// 选中的日期
const selectedDateTimestamp = ref<number>(Date.now())
const selectedDate = computed(() => formatDate(new Date(selectedDateTimestamp.value), 'YYYY-MM-DD'))

// 加载状态
const loading = ref(false)

// 营养素分组
const nutrientGroups = getNutrientFieldGroups()

// 营养数据
const nutritionData = ref<Record<string, number> | null>(null)

// 计算今日营养数据
const calculateNutrition = async () => {
  loading.value = true
  
  try {
    // 获取选中日期的所有饮食事件
    const events = eventsStore.events.filter(event => 
      event.start_date === selectedDate.value && 
      event.extra_data?.foods_intake
    )
    
    if (events.length === 0) {
      nutritionData.value = null
      return
    }
    
    // 累加所有营养素
    const totals: Record<string, number> = {}
    
    events.forEach(event => {
      let foods_intake: FoodIntake[] = []
      
      if (Array.isArray(event.extra_data?.foods_intake)) {
        foods_intake = event.extra_data.foods_intake
      } else if (event.extra_data?.foods_intake?.foods_intake && Array.isArray(event.extra_data.foods_intake.foods_intake)) {
        foods_intake = event.extra_data.foods_intake.foods_intake
      }
      
      foods_intake.forEach(intake => {
        const food = intake.food
        const ratio = intake.amount_g / 100
        
        // 遍历所有营养素字段
        nutrientGroups.forEach(group => {
          group.fields.forEach(field => {
            const value = food[field.key as keyof Food]
            if (value !== undefined && typeof value === 'number') {
              if (!totals[field.key]) {
                totals[field.key] = 0
              }
              totals[field.key] += value * ratio
            }
          })
        })
      })
    })
    
    nutritionData.value = totals
  } finally {
    loading.value = false
  }
}

// 监听日期变化
watch(selectedDate, () => {
  calculateNutrition()
})

// 获取营养素摄入量
const getNutrientIntake = (key: string): string => {
  if (!nutritionData.value || !nutritionData.value[key]) return '0'
  return nutritionData.value[key].toFixed(1)
}

// 获取营养素充足度
const getNutrientAdequacy = (key: string, nutrientId: number): number => {
  if (!nutritionData.value || !nutritionData.value[key]) return 0
  const adequacy = calculateNutrientAdequacy(nutritionData.value[key], nutrientId)
  return adequacy ? Math.min(adequacy, 150) : 0 // 最大显示150%
}

// 获取营养素状态颜色
const getNutrientStatusColor = (key: string, nutrientId: number): string => {
  if (!nutritionData.value || !nutritionData.value[key]) return '#ccc'
  const status = evaluateNutrientStatus(nutritionData.value[key], nutrientId)
  
  switch (status) {
    case 'adequate': return '#52c41a'
    case 'insufficient': return '#faad14'
    case 'excessive': return '#f5222d'
    default: return '#ccc'
  }
}

// 获取营养素状态文本
const getNutrientStatusText = (key: string, nutrientId: number): string => {
  if (!nutritionData.value || !nutritionData.value[key]) return '未知'
  const status = evaluateNutrientStatus(nutritionData.value[key], nutrientId)
  
  switch (status) {
    case 'adequate': return '✓ 达标'
    case 'insufficient': return '⚠️ 不足'
    case 'excessive': return '⚠️ 过量'
    default: return '未知'
  }
}

// 格式化推荐量
const formatRecommendation = (nutrientId: number): string => {
  const rec = getNutrientRecommendation(nutrientId)
  if (!rec) return '无'
  
  if (rec.target !== undefined) {
    return `${rec.target}`
  } else if (rec.min !== undefined && rec.max !== undefined) {
    return `${rec.min}-${rec.max}`
  } else if (rec.max !== undefined) {
    return `<${rec.max}`
  } else if (rec.min !== undefined) {
    return `>${rec.min}`
  }
  
  return '无'
}

// 计算总体评分
const overallScore = computed(() => {
  if (!nutritionData.value) return 0
  
  let totalScore = 0
  let count = 0
  
  nutrientGroups.forEach(group => {
    group.fields.forEach(field => {
      const adequacy = getNutrientAdequacy(field.key, field.nutrientId)
      if (adequacy > 0) {
        // 将充足度转换为评分（80-120%为满分）
        let score = 0
        if (adequacy >= 80 && adequacy <= 120) {
          score = 100
        } else if (adequacy < 80) {
          score = (adequacy / 80) * 100
        } else {
          score = Math.max(0, 100 - (adequacy - 120))
        }
        totalScore += score
        count++
      }
    })
  })
  
  return count > 0 ? totalScore / count : 0
})

// 获取评分颜色
const getScoreColor = (score: number): string => {
  if (score >= 80) return '#52c41a'
  if (score >= 60) return '#faad14'
  return '#f5222d'
}

// 获取评分标签
const getScoreLabel = (score: number): string => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 60) return '及格'
  return '需改善'
}

// 宏量营养素分析
const macroNutrients = computed(() => {
  if (!nutritionData.value) {
    return {
      carb: { grams: 0, kcal: 0, percentage: 0 },
      protein: { grams: 0, kcal: 0, percentage: 0 },
      fat: { grams: 0, kcal: 0, percentage: 0 }
    }
  }
  
  const carbGrams = nutritionData.value['carb_g'] || 0
  const proteinGrams = nutritionData.value['protein_g'] || 0
  const fatGrams = nutritionData.value['fat_g'] || 0
  
  const carbKcal = carbGrams * 4
  const proteinKcal = proteinGrams * 4
  const fatKcal = fatGrams * 9
  
  const totalKcal = carbKcal + proteinKcal + fatKcal
  
  return {
    carb: {
      grams: Math.round(carbGrams * 10) / 10,
      kcal: Math.round(carbKcal),
      percentage: totalKcal > 0 ? (carbKcal / totalKcal) * 100 : 0
    },
    protein: {
      grams: Math.round(proteinGrams * 10) / 10,
      kcal: Math.round(proteinKcal),
      percentage: totalKcal > 0 ? (proteinKcal / totalKcal) * 100 : 0
    },
    fat: {
      grams: Math.round(fatGrams * 10) / 10,
      kcal: Math.round(fatKcal),
      percentage: totalKcal > 0 ? (fatKcal / totalKcal) * 100 : 0
    }
  }
})

// 获取宏量营养素颜色
const getMacroColor = (type: 'carb' | 'protein' | 'fat', percentage: number): string => {
  const ranges = {
    carb: { min: 50, max: 65 },
    protein: { min: 10, max: 20 },
    fat: { min: 20, max: 30 }
  }
  
  const range = ranges[type]
  if (percentage >= range.min && percentage <= range.max) {
    return '#52c41a'
  } else if (percentage < range.min * 0.8 || percentage > range.max * 1.2) {
    return '#f5222d'
  }
  return '#faad14'
}

// 初始化
onMounted(async () => {
  await eventsStore.init()
  await calculateNutrition()
})
</script>

<style scoped>
.nutrition-dashboard {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.date-selector {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-state p {
  margin: 16px 0 24px;
  color: #666;
  font-size: 16px;
}

.nutrition-content {
  padding: 16px;
}

.overall-score,
.macro-analysis,
.nutrients-list {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.overall-score h3,
.macro-analysis h3,
.nutrients-list h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.score-circle {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.score-text {
  text-align: center;
}

.score-value {
  font-size: 32px;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 4px;
}

.score-label {
  font-size: 14px;
  color: #666;
}

.macro-item {
  margin-bottom: 20px;
}

.macro-item:last-child {
  margin-bottom: 0;
}

.macro-label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.progress-text {
  font-size: 12px;
  color: white;
  font-weight: 500;
}

.macro-recommendation {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.nutrient-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.nutrient-item {
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.nutrient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.nutrient-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.nutrient-value {
  font-size: 14px;
  font-weight: 600;
  color: #667eea;
}

.nutrient-progress {
  margin-top: 8px;
}

.nutrient-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;
}

.recommendation {
  color: #999;
}

.status {
  font-weight: 500;
}
</style>

